package ace.module.upms.core.impl.dao.aggregate.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.module.upms.core.impl.dao.aggregate.UpmsMenuAggregate;
import ace.module.upms.core.impl.dao.entity.*;
import ace.module.upms.core.impl.dao.repository.UpmsMenuRepository;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
* 菜单权限 aggregate implement.
*
* @author Caspar
*/
@Slf4j
@AllArgsConstructor
@Component
public class UpmsMenuAggregateImpl implements UpmsMenuAggregate {
  private final UpmsMenuRepository upmsMenuRepository;

  @Override
  public List<UpmsMenu> getByUpmsAppIdAndAccountIdAndDeleteFlagIsNot(
      Long upmsAppId, Long accountId) {
    QUpmsRoleAccount qRoleAccount = QUpmsRoleAccount.upmsRoleAccount;
    QUpmsRoleMenu qRoleMenu = QUpmsRoleMenu.upmsRoleMenu;
    QUpmsRole qRole = QUpmsRole.upmsRole;
    QUpmsMenu qMenu = QUpmsMenu.upmsMenu;
    List<UpmsMenu> menus =
        upmsMenuRepository.query(
            sqlQuery ->
                sqlQuery
                    .select(qMenu)
                    .from(qMenu)
                    .innerJoin(qRoleMenu)
                    .on(qRoleMenu.menuId.eq(qMenu.id))
                    .innerJoin(qRole)
                    .on(qRole.id.eq(qRoleMenu.roleId))
                    .innerJoin(qRoleAccount)
                    .on(qRoleAccount.roleId.eq(qRole.id))
                    .where(qRoleAccount.iamAccountId.eq(accountId))
                    .where(qRoleAccount.upmsAppId.eq(upmsAppId))
                    .where(qMenu.deleteFlag.eq(CoreConstant.DELETE_FLAG_NOT))
                    .where(qRoleAccount.deleteFlag.eq(CoreConstant.DELETE_FLAG_NOT))
                    .where(qRole.deleteFlag.eq(CoreConstant.DELETE_FLAG_NOT))
                    .distinct()
                    .fetch());
    return menus;
  }
}
